import requests
import re
import json
import random
import os
from urllib.parse import urljoin

random_integer = random.randint(0, 999999)

headers = {
    "Referer": "https://secure.elong.com/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",

}
url = "https://turing.captcha.qcloud.com/cap_union_prehandle"
params = {
    "aid": "199680628",
    "protocol": "https",
    "accver": "1",
    "showtype": "popup",
    "ua": "TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzEyMS4wLjAuMCBTYWZhcmkvNTM3LjM2",
    "noheader": "1",
    "fb": "1",
    "aged": "0",
    "enableAged": "0",
    "enableDarkMode": "0",
    "grayscale": "1",
    "clientype": "2",
    "cap_cd": "",
    "uid": "",
    "lang": "zh-cn",
    "entry_url": "https://secure.elong.com/passport/login_cn.html",
    "elder_captcha": "0",
    "js": "/tcaptcha-frame.22125576.js",
    "login_appid": "",
    "wb": "1",
    "subsid": "1",
    "callback": f"_aq_{random_integer}",
    "sess": ""
}
response = requests.get(url, headers=headers, params=params)

data = response.text
data_dict = json.loads(data.strip(f"_aq_{random_integer}").strip("(").strip(")"))
img_url = data_dict["data"]["dyn_show_info"]["bg_elem_cfg"]["img_url"]
base_url, image_num, session = img_url.split("&")

result_img_url = urljoin("https://turing.captcha.qcloud.com", base_url)
image = image_num.split("=")[1]
sess = session.split("=")[1]

params = {
    "image": image,
    "sess": sess
}

response = requests.get(result_img_url, headers=headers, params=params)

with open("1.png", "wb") as f:
    f.write(response.content)
